import * as THREE from '../../build/three.module.js';
import Stats from '../../jsm/libs/stats.module.js';

import { OrbitControls } from '../../jsm/controls/OrbitControls.js';
import { OBJLoader } from '../../jsm/loaders/OBJLoader.js';

// 折射与反射贴图路径
const path = '../../textures/cube/SwedishRoyalCastle/';
const format = '.jpg';
const url = [
  path + 'px' + format, path + 'nx' + format,
  path + 'py' + format, path + 'ny' + format,
  path + 'pz' + format, path + 'nz' + format
];

// 反射贴图
const reflectionCubeMap = new THREE.CubeTextureLoader().load( url );
reflectionCubeMap.format = THREE.RGBFormat;

// 折射贴图
const refractionCubeMap = new THREE.CubeTextureLoader().load( url );
refractionCubeMap.format = THREE.RGBFormat;
refractionCubeMap.mapping = THREE.CubeRefractionMapping;

// 场景
const scene = new THREE.Scene();
scene.background = reflectionCubeMap;

// 相机
const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 1, 5000);
camera.position.z = 2000;

// 渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

// 环境光
scene.add( new THREE.AmbientLight( 0xffffff ) );

// 点光源
const pointL = new THREE.PointLight( 0xffffff, 2 );
scene.add(pointL);

// 材质
const cubeMaterial3 = new THREE.MeshLambertMaterial({ color: 0xff6600, envMap: reflectionCubeMap, combine: THREE.MixOperation, reflectivity: 0.3 });
const cubeMaterial2 = new THREE.MeshLambertMaterial({ color: 0xffee00, envMap: refractionCubeMap, refractionRatio: 0.95 });
const cubeMaterial1 = new THREE.MeshLambertMaterial({ color: 0xffffff, envMap: reflectionCubeMap });

// 加载网格模型
const loader = new OBJLoader();
loader.setPath('../../models/obj/walt/');
loader.load('WaltHead.obj', object => {
  const headMesh = object.children[0];

  headMesh.scale.multiplyScalar(15);
  headMesh.position.y = -500;
  headMesh.material = cubeMaterial1;

  const headMesh2 = headMesh.clone();
  headMesh2.position.x = 900;
  headMesh2.material = cubeMaterial2;

  const headMesh3 = headMesh.clone();
  headMesh3.position.x = -900;
  headMesh3.material = cubeMaterial3;

  scene.add(headMesh, headMesh2, headMesh3);
})

// 控制器
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableZoom = false;
controls.enablePan = false;
controls.minPolarAngle = Math.PI / 4;
controls.maxPolarAngle = Math.PI / 1.5;

// 统计器
const stats = new Stats();
document.body.appendChild(stats.dom);

// 动画驱动
const animate = () => {
  requestAnimationFrame(animate);

  stats.update();
  renderer.render(scene, camera);
}
animate();

// 事件绑定
const handleWindowResize = () => {

  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(innerWidth, innerHeight);

}
handleWindowResize();
window.addEventListener('resize', handleWindowResize, false);
